package com.weizai.carshop.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weizai.carshop.common.enumeration.AppHttpCodeEnum;
import com.weizai.carshop.common.result.PageResult;
import com.weizai.carshop.common.result.ResponseResult;
import com.weizai.carshop.mapper.ShopCateMapper;
import com.weizai.carshop.model.dto.QueryShopCateDto;
import com.weizai.carshop.model.dto.ShopCateDto;
import com.weizai.carshop.model.entiity.ShopCateEntity;
import com.weizai.carshop.model.entiity.ShopCateInfoEntity;
import com.weizai.carshop.service.ShopCateService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ShopCateServiceImpl extends ServiceImpl<ShopCateMapper, ShopCateEntity> implements ShopCateService {

    /*
     * 新增或编辑分类列表
     * */
    @Override
    public void insert(ShopCateDto dto) {
        // 拷贝数据
        ShopCateEntity shopCateEntity = BeanUtil.copyProperties(dto, ShopCateEntity.class);
        // 添加时间
        if (shopCateEntity.getId() == null) {
            shopCateEntity.setCreateTime(LocalDateTime.now());
            shopCateEntity.setUpdateTime(LocalDateTime.now());
        }else {
            shopCateEntity.setUpdateTime(LocalDateTime.now());
        }

        // 保存或更新
        this.saveOrUpdate(shopCateEntity);
    }


    /*
     * 条件查询列表
     * */
    @Override
    public PageResult queryPage(QueryShopCateDto dto) {

        // 设置分页判断
        dto.validate();

        // 查询
        Page<ShopCateEntity> page = this.lambdaQuery()
                .like(dto.getKeywords() != null, ShopCateEntity::getTitle, dto.getKeywords())
                .page(new Page<>(dto.getPage(), dto.getPageSize()));


        return new PageResult(page.getTotal(), page.getRecords());
    }


    /*
    * 删除分类
    * */
    @Override
    public ResponseResult delCateById(Long id) {

        // 查询当前分类下是否有关联
        List<ShopCateInfoEntity> cateInfo = Db.lambdaQuery(ShopCateInfoEntity.class)
                .eq(ShopCateInfoEntity::getCateId, id)
                .list();

        if(!cateInfo.isEmpty() || cateInfo.size() > 0) {
            return ResponseResult.errorResult(500, "当前分类下有商品，无法删除");
        }


        // 执行删除操作
        baseMapper.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
